var express = require('express');
const UserModel = require('../../module/userModel');
const md5 = require('md5');
var router = express.Router();

router.get('/reg', (req, res)=>{
    res.render('auth/reg')
})

router.post('/reg', (req, res)=>{
    UserModel.create({...req.body,password:md5(req.body.password)},(err, data)=>{
        if(err){
            res.status(500).send('注册用户失败')
            return
        }
        res.render('success', {msg:'注册成功',url:'/login'})
    })
})

router.get('/login', (req, res)=>{
    res.render('auth/login')
})

router.post('/login', (req, res)=>{
    let {username,password} = req.body
    UserModel.findOne({username,password:md5(password)},(err, data)=>{
        if(err){
            return res.status(500).send('查询用户失败')
        }
        if(!data){
            return res.status(500).send('用户不存在')
        }
        req.session.username = username
        req.session._id = data._id
        res.render('success',{msg:'登录成功',url:'/account'})
    })
})

router.post('/logout',(req,res)=>{
    req.session.destroy(()=>{
        res.render('success', {msg:'退出成功',url:'/login'})
    })
})

module.exports = router;
